package com.fable.sp.core.service.impl;

import com.fable.sp.core.widget.RenderResponse;
import org.springframework.web.util.WebUtils;

import java.io.*;

/**
 * .
 *
 * @author stormning on 16/8/8.
 */
public class RenderResponseImpl extends WidgetResponseImpl implements RenderResponse {
    private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
    private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING;
    private PrintWriter writer;
    private int bufferSize = 4096;
    private boolean committed;

    private String includedUrl;

    private String forwardedUrl;

    @Override
    public PrintWriter getWriter() throws IOException {
        if (this.writer == null) {
            Writer targetWriter = (this.characterEncoding != null ?
                    new OutputStreamWriter(this.outputStream, this.characterEncoding) :
                    new OutputStreamWriter(this.outputStream));
            this.writer = new PrintWriter(targetWriter);
        }
        return this.writer;
    }

    @Override
    public int getBufferSize() {
        return this.bufferSize;
    }

    @Override
    public void setBufferSize(int bufferSize) {
        this.bufferSize = bufferSize;
    }

    @Override
    public void flushBuffer() throws IOException {
        if (this.writer != null) {
            this.writer.flush();
        }
        try {
            this.outputStream.flush();
        } catch (IOException ex) {
            throw new IllegalStateException("Could not flush OutputStream: " + ex.getMessage());
        }
        this.committed = true;
    }

    @Override
    public void resetBuffer() {
        if (this.committed) {
            throw new IllegalStateException("Cannot reset buffer - response is already committed");
        }
        this.outputStream.reset();
    }

    @Override
    public boolean isCommitted() {
        return this.committed;
    }

    public void setCommitted(boolean committed) {
        this.committed = committed;
    }

    @Override
    public void reset() {
        resetBuffer();
        this.characterEncoding = null;
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        return this.outputStream;
    }

    public String getIncludedUrl() {
        return this.includedUrl;
    }

    public void setIncludedUrl(String includedUrl) {
        this.includedUrl = includedUrl;
    }

    public String getForwardedUrl() {
        return this.forwardedUrl;
    }

    public void setForwardedUrl(String forwardedUrl) {
        this.forwardedUrl = forwardedUrl;
    }
}
